<template>
  <el-form
    ref="form"
    label-width="80px"
    size="small"
    style="margin-top: 2%; margin-left: 1%"
  >
    <!-- <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="">
        <el-input
          v-model="input1"
          placeholder="请输入表头内容"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="onSubmit"
          >搜索</el-button
        >
        <el-button
          type="warning"
          icon="el-icon-refresh"
          size="mini"
          @click="clear"
          >重置</el-button
        >
      </el-form-item>
    </el-form> -->
    <el-button
      type="primary"
      plain
      icon="el-icon-plus"
      size="mini"
      @click="handleAdd()"
    >新增</el-button>
    <el-button
      type="warning"
      plain
      icon="el-icon-view"
      size="mini"
      style="margin-left: 1%"
      @click="preview"
    >预览</el-button>
    <el-table
      v-loading="loading"
      :data="tableData"
      style=""
      @selection-change="handleSelectionChange"
    >
      <el-table-column prop="name" label="表头名称" align="center" />
      <el-table-column prop="sort" label="序号" align="center" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deleteById(scope.row.id)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增表头弹框 -->
    <el-dialog
      ref="form"
      :title="title"
      :visible.sync="dialogVisible2"
      width="30%"
    >
      <el-form
        ref="form"
        :model="tableHeader"
        :rules="rules"
        label-width="80px"
        size="mini"
      >
        <el-form-item prop="name" label="表头名称">
          <el-input
            v-model="tableHeader.name"
            placeholder="请输入内容"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item prop="sort" label="序号">
          <el-input
            v-model="tableHeader.sort"
            type="number"
            placeholder="请输入内容"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item style="margin-left: 15%">
          <el-button type="primary" @click="add_header">提交</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 预览弹框 -->
    <el-dialog
      ref="form"
      title="表头预览"
      :visible.sync="dialogVisible4"
      width="60%"
      style="margin-top: 10%"
    >
      <el-form ref="form" size="small">
        <el-table
          v-loading="loading"
          style="margin-top: -5%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            v-for="item in tableData"
            :key="item._key"
            :prop="item._key"
            :label="item.name"
            align="center"
          />
        </el-table>
      </el-form>
    </el-dialog>
  </el-form>
</template>

<script>
import {
  add_header,
  page_id,
  query_header,
  update_header,
  delete_header
} from '@/api/files_1.js'
import { parseTime } from '@/utils'
import { mapState, mapMutations } from 'vuex'
export default {
  data() {
    return {
      input1: '',
      input2: '',
      tableHeader: {
        name: '',
        sort: undefined
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        sort: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      loading: false,
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,

      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible2: false,
      dialogVisible3: false,
      dialogVisible4: false,
      queryParams: {
        status: '',
        createTime: '', // 添加开始时间字段
        endTime: '' // 添加结束时间字段
      },
      entryDate: [], // 用于v-model绑定日期选择器的值
      value: {},
      createTime: '',
      endTime: '',
      title: '',
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      tableKey: 0,
      list: null,
      total: 0
    }
  },
  computed: {
    ...mapState(['name'])
  },

  mounted() {
    this.zlId = this.$route.params.id
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },

  methods: {
    onSubmit() {
      this.page()
    },
    // 查询分页数据
    page() {
      page_id(this.zlId)
        .then((res) => {
          if (res.code === 1) {
            // 确保响应成功
            this.totalCount = res.data.length
            this.tableData = res.data
          } else {
            console.error('API 请求未成功，响应码：', res.code)
          }
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },
    // 表单重置
    reset() {
      this.tableHeader = {
        name: '',
        sort: undefined,
        docuId: this.zlId
      }
    },
    handleAdd(row) {
      this.reset()
      this.dialogVisible2 = true
      this.title = '新增表头'
    },

    handleUpdate(row) {
      this.reset()
      const id = row.id
      // 根据id获取表头
      query_header(id).then((response) => {
        this.tableHeader = response.data

        this.dialogVisible2 = true
        this.title = '修改表头'
      })
    },
    handleDateChange(val) {
      if (val) {
        this.queryParams.createTime = val[0] // 开始时间
        this.queryParams.endTime = val[1] // 结束时间
      } else {
        this.queryParams.createTime = ''
        this.queryParams.endTime = ''
      }
    },
    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 重置方法
    clear() {
      this.queryParams.status = ''
      this.entryDate = []
      this.page()
    },
    // 添加数据
    add_header() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let operator
          if (this.tableHeader.id) {
            // 修改
            operator = update_header(this.tableHeader)
          } else {
            operator = add_header(this.tableHeader)
          }

          operator.then((resp) => {
            if (resp.code === 1) {
              this.dialogVisible2 = false
              this.$message({ message: '保存成功', type: 'success' })
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
          // 将输入的数据保存到数组中
          this.tableData.push({
            name: this.input1,
            sequence: this.input2
          })
        } else {
          return false
        }
      })
    },
    preview() {
      // 1. 打开窗口
      this.dialogVisible4 = true
      // 对数组进行排序
      this.tableData.sort((a, b) => a.sequence - b.sequence)

      // 显示预览弹框
      this.dialogVisible4 = true
    },
    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delete_header({ id: id }).then((resp) => {
            if (resp.code == 1) {
              // 删除成功
              this.$message.success('恭喜你，删除成功')
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },

    ...mapMutations('schoolmanage', ['getname']),
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped>
/* 全局CSS 或者在<style scoped>内 */
.el-form-item .is-disabled .el-input__inner,
.is-disabled .el-date-editor.el-input__inner {
  background-color: #f5f7fa;
  /* 变更输入框背景色 */
  color: #c0c4cc;
  /* 变更文字颜色 */
  cursor: not-allowed;
  /* 更改鼠标指针形状 */
}

/* 如果需要单独针对学期学年（el-select）调整样式 */
.el-form-item .is-disabled .el-select .el-input__inner {
  /* 在这里添加特定于el-select的样式 */
}
</style>
